package cn.edu.ncut.cs.springboot.petmanagementsystem.service.Impl;

import cn.edu.ncut.cs.springboot.petmanagementsystem.common.PageResult;
import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.MessageMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.Message;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 消息通知服务实现类
 */
@Slf4j
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    /**
     * 获取用户消息列表
     */
    @Override
    public PageResult<Message> getMessageList(Long userId, Integer page, Integer pageSize) {
        log.info("获取用户消息列表，用户ID：{}，页码：{}，每页大小：{}", userId, page, pageSize);

        // 参数默认值
        if (page == null || page < 1) {
            page = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }

        // 计算偏移量
        int offset = (page - 1) * pageSize;

        // 查询消息列表
        List<Message> messages = messageMapper.selectByUserId(userId, offset, pageSize);

        // 查询总数
        Integer total = messageMapper.countByUserId(userId);
        if (total == null) {
            total = 0;
        }

        // 使用PageResult的静态方法创建分页结果
        return PageResult.success(messages, total.longValue(), (long) page, (long) pageSize);
    }

    /**
     * 标记消息已读
     */
    @Override
    @Transactional
    public boolean markAsRead(Long id, Long userId) {
        log.info("标记消息已读，消息ID：{}，用户ID：{}", id, userId);

        Integer rows = messageMapper.markAsRead(id, userId);
        return rows > 0;
    }

    /**
     * 删除消息
     */
    @Override
    @Transactional
    public boolean deleteMessage(Long id, Long userId) {
        log.info("删除消息，消息ID：{}，用户ID：{}", id, userId);

        // 验证消息归属
        Message message = messageMapper.selectById(id);
        if (message == null) {
            throw new RuntimeException("消息不存在");
        }
        if (!message.getUserId().equals(userId)) {
            throw new RuntimeException("无权删除此消息");
        }

        int rows = messageMapper.deleteById(id);
        return rows > 0;
    }

    /**
     * 获取未读消息数量
     */
    @Override
    public Integer getUnreadCount(Long userId) {
        log.info("获取未读消息数量，用户ID：{}", userId);

        return messageMapper.countUnreadByUserId(userId);
    }
}
